package org.fxd.zweixin.busi_login.login.web;

import org.apache.commons.lang3.RandomStringUtils;
import org.fxd.zweixin.busi_login.login.domain.dto.ForgetPwdDTO;
import org.fxd.zweixin.busi_login.login.domain.dto.LoginDTO;
import org.fxd.zweixin.busi_login.login.service.LoginService;
import org.fxd.zweixin.busi_system.user.domian.po.t_user;
import org.fxd.zweixin.util.CookieUtil;
import org.fxd.zweixin.util.SessionTool;
import org.fxd.zweixin.util.WebTools;
import org.fxd.zweixin.util.sms.SmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.tmsps.ne4spring.base.BaseAction;
import org.tmsps.ne4spring.utils.JsonUtil;
import org.tmsps.ne4spring.utils.WebUtil;
import org.tmsps.ne4spring.utils.wrapper.WrapMapper;
import org.tmsps.ne4spring.utils.wrapper.Wrapper;

import com.alibaba.fastjson.JSONObject;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "登录")
@RestController
public class LoginAction extends BaseAction {

	@Autowired
	private LoginService loginService;

	@ApiOperation(value = "登录")
	@GetMapping("/login")
	public Wrapper<JSONObject> login(LoginDTO loginDTO) {
		JSONObject result = loginService.login(loginDTO);
		return WrapMapper.ok(result);
	}

	@ApiOperation(value = "退出登录")
	@GetMapping("/login_out")
	public Wrapper<String> loginout() {
		WebTools.getRequest().getSession().invalidate();
		CookieUtil.clearCookie();
		return WrapMapper.ok("退出成功!");
	}

	@ApiOperation(value = "获取当前登录人员")
	@GetMapping("/app/get_current")
	public Wrapper<t_user> get_current() {
		t_user user = bs.findById(SessionTool.getSessionUserId(), t_user.class);
		return WrapMapper.ok(user);
	}

	@ApiOperation(value = "忘记密码")
	@GetMapping("/forget_pwd")
	public Wrapper<JSONObject> forget_pwd(ForgetPwdDTO forgetPwdDTO) {
		JSONObject result = loginService.forgetPwd(forgetPwdDTO);
		return WrapMapper.ok(result);
	}

	@ApiOperation(value = "发送验证码")
	@GetMapping("/sendSms")
	public Wrapper<String> sendSms(String mobile) {
		String sms_code = RandomStringUtils.randomNumeric(4);
		WebUtil.getSession().setAttribute("sms_code", sms_code);
		String content = "您注册的短信验证码为:" + sms_code;
		String send = SmsUtil.send(mobile, content);
		logger.info("mobile={},content={}", mobile, content);
		JSONObject json = JsonUtil.jsonStrToJsonObject(send);
		if (json.getBooleanValue("success")) {
			return WrapMapper.ok("发送成功");
		} else {
			return WrapMapper.ok("发送失败,请联系管理员.");
		}
	}

}
